package com.example.bicycle.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.util.SaResult;
import com.example.bicycle.domain.dto.UserLocationDto;
import com.example.bicycle.domain.entity.RideRecord;
import com.example.bicycle.domain.vo.BikeLocationVo;
import com.example.bicycle.service.BatteryService;
import com.example.bicycle.service.ElectricBikeService;
import com.example.bicycle.service.RideRecordService;
import com.example.bicycle.utils.DistanceUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@SaCheckLogin
@RestController
@RequestMapping("/user/")
public class UserController {
    private final ElectricBikeService electricBikeService;
    private final RideRecordService rideRecordService;
    private final BatteryService batteryService;

    @Autowired
    public UserController(ElectricBikeService electricBikeService, RideRecordService rideRecordService, BatteryService batteryService) {
        this.electricBikeService = electricBikeService;
        this.rideRecordService = rideRecordService;
        this.batteryService = batteryService;
    }


    /**
     * 租车状态（返回租车情况）
     *
     * @param userLocationDto 用户位置dto
     * @return {@link SaResult}
     */
    @PostMapping("borrowSituation")
    public SaResult borrowSituation(@RequestBody UserLocationDto  userLocationDto) {
        RideRecord latestRideRecord = rideRecordService.getLatestRecordByUserId(userLocationDto.getUserId());

        if(latestRideRecord!=null&&latestRideRecord.getEndTime()==null){
            BikeLocationVo  bikeLocationVo = new BikeLocationVo();
            bikeLocationVo.setBike(electricBikeService.getById(latestRideRecord.getBikeId()));
            bikeLocationVo.setRideRecord(latestRideRecord);
            bikeLocationVo.setDistance(DistanceUtils.getDistance(bikeLocationVo.getBike().getLongitude(),bikeLocationVo.getBike().getLatitude(),userLocationDto.getLongitude(),userLocationDto.getLatitude()));
            bikeLocationVo.setBattery(batteryService.getById(bikeLocationVo.getBike().getBatteryId()));
            return SaResult.data(bikeLocationVo);
        }
        return SaResult.error("该用户未租车");
    }
}
